package com.xin.di.uav.applet.rest;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xin.di.uav.utils.HttpClientUtil;
import com.xin.di.uav.applet.utils.SignatureUtils;
import com.xin.di.uav.common.response.order.task.TaskStatusLogResponse;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * @author 01430312
 */
@RequiredArgsConstructor
@Component
@RestController
public class SysTcRest {

    private final static Logger logger = LoggerFactory.getLogger(SysTcRest.class);


    @Value("${tc.dev_id:1705100313}")
    private String tcDevId;

    @Value("${tc.app_key:f2b83ce49267f26ff3e46101cea43592}")
    private String tcAppKey;

    @Value("${tc.url:https://externaltc.sf-express.com/b82920ea10cc11fd}")
//    @Value("${tc.url:https://externaltc.sf-express.com/c776e2e013b9e709}")
    private String tcUrl;


    @Value("${new-proxy-url:IE-UOCS-CORE-3adm832e.lbsit.sfcloud.local}")
    private String newProxyUrl;

//    @Value("${is-use-proxy:false}")
//    private boolean isUseProxy;

    public JSONObject getRiderLatestPosition(String orderId) {
        try {

            return null;


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JSONObject getOrderInfo(String orderId) {
        try {


            JSONObject postData = new JSONObject();
            postData.put("dev_id", tcDevId);
            postData.put("order_id", orderId);
            postData.put("push_time", System.currentTimeMillis() / 1000);
            String sign = SignatureUtils.generateOpenSign(postData.toString(), Long.valueOf(tcDevId), tcAppKey);
            String body = HttpClientUtil.sendPostJsonRepeatProxy(tcUrl + "/open/api/external/getorderstatus?sign=" + sign, postData.toString(), newProxyUrl, 80, true);
            logger.info("同城跑腿订单id: {} ,调用顺丰同城API查询结果为: {}", orderId, body);
            Integer errorCode = JSONObject.parseObject(body).getInteger("error_code");
            if (errorCode.equals(0)) {
                return JSONObject.parseObject(JSONObject.parseObject(body).getString("result"));
            }
            return null;


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public List<TaskStatusLogResponse> getListOrderFeed(String orderId) {
        try {
            //获取秒级时间戳
            long timestamp = System.currentTimeMillis() / 1000;
            JSONObject params = new JSONObject();
            params.put("dev_id", tcDevId);
            params.put("order_id", orderId);
            params.put("push_time", String.valueOf(timestamp));
            String sign = SignatureUtils.generateOpenSign(params.toString(), Long.valueOf(tcDevId), tcAppKey);
            logger.info("同城跑腿订单id: {} ,调用顺丰同城API入参为: {}", orderId, params.toString());
            String body = HttpClientUtil.sendPostJsonRepeatProxy(tcUrl + "/open/api/external/listorderfeed?sign=" + sign, params.toString(), newProxyUrl, 80, true);
//            HttpResponse<String> response = Unirest.post(tcUrl + "/open/api/external/listorderfeed?sign=" + sign).header("User-Agent", "Apifox/1.0.0 (https://apifox.com)").body(params.toString()).asString();
//            String body = response.getBody();
            logger.info("同城跑腿订单id: {} ,调用顺丰同城API查询结果为: {}", orderId, body);
            JSONObject jsonBody = JSON.parseObject(body);
            if (!jsonBody.getInteger("error_code").equals(0)) {
                logger.info("订单状态流查询失败");
                String errMsg = jsonBody.getString("error_msg");
                logger.info(errMsg);
                return null;
            }
            JSONObject result = JSON.parseObject(jsonBody.getString("result"));
            JSONArray feed = result.getJSONArray("feed");
            List<TaskStatusLogResponse> taskStatusLogResponses = new LinkedList<>();

            for (int i = 0; i < feed.size(); i++) {
                TaskStatusLogResponse taskStatusLogResponse = new TaskStatusLogResponse();

                // 获取每个位置上的JSONObject
                JSONObject jsonObject = feed.getJSONObject(i);

                // 从JSONObject中获取键值对
                Integer orderStatus = jsonObject.getInteger("order_status");
                Date createTime = jsonObject.getDate("create_time");
                taskStatusLogResponse.setStatus(orderStatus);
                taskStatusLogResponse.setCreateTime(createTime);
                taskStatusLogResponses.add(taskStatusLogResponse);
                logger.info("同城订单状态记录 {}：\n{}", i, JSONObject.toJSONString(taskStatusLogResponses));
            }
            if (CollUtil.isEmpty(taskStatusLogResponses)) {
                return null;
            }
            return new ArrayList<>(taskStatusLogResponses.stream().collect(Collectors.toMap(
                    TaskStatusLogResponse::getCreateTime, // 使用时间作为去重字段
                    Function.identity(), // 值就是Item本身
                    (existing, replacement) -> existing // 如果有冲突，保留现有的值
            )).values()).stream()
                    .sorted(Comparator.comparing(TaskStatusLogResponse::getCreateTime))
                    .collect(Collectors.toList());
        } catch (Exception e) {
            logger.info("同城跑腿订单id: {} ,查询同城订单状态流失败----->{}", orderId, e.getMessage());
            throw new RuntimeException(e);
        }
    }


    public JSONObject cancelOrder(String orderId) {
        try {
            //获取秒级时间戳
            long timestamp = System.currentTimeMillis() / 1000;
            JSONObject params = new JSONObject();
            params.put("dev_id", tcDevId);
            params.put("order_id", orderId);
            params.put("push_time", timestamp);
            String sign = SignatureUtils.generateOpenSign(params.toString(), Long.valueOf(tcDevId), tcAppKey);
            String body = HttpClientUtil.sendPostJsonRepeatProxy(tcUrl + "/open/api/external/cancelorder?sign=" + sign, params.toString(), newProxyUrl, 80, true);
            logger.info("同城跑腿订单id: {} ,调用顺丰同城API查询结果为: {}", orderId, body);
            Integer errorCode = JSONObject.parseObject(body).getInteger("error_code");
            if (errorCode.equals(0)) {
                return JSONObject.parseObject(JSONObject.parseObject(body).getString("result"));
            }
            return null;


        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Boolean testNetWork(String hostName, Integer timeout) {
        try {
            return InetAddress.getByName(hostName).isReachable(timeout);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
